var app = new Vue({
	el: '#app',
	data: {
		id: "",
		name: "",
		roomId: "",
		dataList: [],
		myvddata: {},
		cameraType: "user",
		cameraChangeLoading: false,
	},
	mounted(e) {
		console.log(33995,config)
		const _this = this
		window.addEventListener('message', e => {
			console.log(e, 'HTML接受APP');
			_this.receviceMessage(JSON.parse(e.data))
			// app.receviceMessage(e.data.data)
		}, false)
		window.addEventListener("beforeunload", function() {
			for (let o of _this.dataList) {
				try {
					if (o.id == _this.id) {
						o.unpublish()
					} else {
						o.close()
					}
				} catch (e) {
					//TODO handle the exception
				}
			}
			uni.postMessage({
				data: {
					type: "exitmtroom",
					payload: {

					}
				}
			});
		})
	},
	onLoad(e) {
		console.log(11, e)
		const id = e.id
		this.name = this.name + "_" + id
	},
	onShow(e) {
		console.log(22, e)
	},
	methods: {
		receviceMessage: function(e) {
			console.log(e.type, e.payload)
			if (e.type == "backpress") {
				this.exit()
			}
			if (e.type == "setStreams") {
				const streams = e.payload
				const ids = this.dataList.map(e => e.id * 1)
				for (let o of streams) {
					if (ids.includes(o.id * 1)) {
						continue
					}
					this.subStream({
						id: o.id * 1,
						name: o.name,
						roomId: this.roomId,
						audio: o.audio,
						video: o.video,
						avatar: o.avatar
					})
				}
			}

			if (e.type == "userJoin") {
				for (let o of this.dataList) {
					if (o.id * 1 == e.payload.id * 1) {
						return
					}
				}
				this.subStream({
					id: e.payload.id * 1,
					name: e.payload.name,
					roomId: this.roomId,
					audio: e.payload.audio,
					video: e.payload.video,
					avatar: e.payload.avatar
				})
			}

			if (e.type == "userLeave") {
				let newarr = []
				for (let o of this.dataList) {
					if (o.id * 1 == e.payload.id * 1) {
						o.close()
					} else {
						newarr.push(o)
					}
				}
				this.dataList = newarr
				this.reloadvd()
			}

			if (e.type == "userMuteAudio") {
				for (let o of this.dataList) {
					if (o.id == e.payload.id) {
						o.audio = false
						break
					}
				}
			}

			if (e.type == "userResumeAudio") {
				for (let o of this.dataList) {
					if (o.id == e.payload.id) {
						o.audio = true
						break
					}
				}
			}

			if (e.type == "userCloseVideo") {
				for (let o of this.dataList) {
					if (o.id == e.payload.id) {
						o.video = false
						break
					}
				}
			}

			if (e.type == "userOpenVideo") {
				for (let o of this.dataList) {
					if (o.id == e.payload.id) {
						o.video = true
						setTimeout(() => {
							document.getElementById("vd_" + o.id).srcObject = o.stream
						}, 1000)
						break
					}
				}
			}
		},
		reloadvd: function() {
			for (let o of this.dataList) {
				setTimeout(() => {
					document.getElementById("vd_" + o.id).srcObject = o.stream
				}, 300)
			}
		},
		exit: function() {
			for (let o of this.dataList) {
				try {
					if (o.id == this.id) {
						o.unpublish()
					} else {
						o.close()
					}
				} catch (e) {
					//TODO handle the exception
				}
			}
			uni.postMessage({
				data: {
					type: "exitmtroom",
					payload: {

					}
				}
			});
			uni.switchTab({
				url: "/pages/meeting/index"
			})
		},
		initData: function(e) {
			this.name = decodeURI(e.name)
			this.id = e.id
			this.roomId = e.roomId
		},
		changeCamera: function() {
			this.cameraChangeLoading = true
			this.cameraType = this.cameraType == "environment" ? "user" : "environment"
			this.myvddata.unpublish()
			uni.postMessage({
				data: {
					type: "exitmtroom",
					payload: {

					}
				}
			});
			const _this = this
			setTimeout(() => {
				_this.cameraChangeLoading = false
				// _this.publishStream({
				// 	video: _this.myvddata.video,
				// 	audio: _this.myvddata.audio,
				// 	videoType: _this.cameraType
				// })
				_this.publishScreenStream({
					video:true,audio:false
				})
			}, 1000)
		},
		muteAudio: function(type) {
			console.log(this.myvddata)
			this.myvddata.muteAudio(type)
			this.myvddata.audio = type ?? false
			// for (let o of this.dataList) {
			// 	if (o.id == this.myvddata.id) {
			// 		o.audio = type ?? false
			// 		break
			// 	}
			// }
			if (type) {
				uni.postMessage({
					data: {
						type: "resumeAudio",
						payload: {
							roomId: this.roomId
						}
					}
				});
			} else {
				uni.postMessage({
					data: {
						type: "muteAudio",
						payload: {
							roomId: this.roomId
						}
					}
				});
			}
		},
		muteVideo: function(type) {
			console.log(this.myvddata)
			this.myvddata.muteVideo(type)
			this.myvddata.video = type
			// for (let o of this.dataList) {
			// 	if (o.id == this.myvddata.id) {
			// 		o.video = type
			// 		break
			// 	}
			// }
			if (type) {
				uni.postMessage({
					data: {
						type: "openVideo",
						payload: {
							roomId: this.roomId
						}
					}
				});
				// setTimeout(() => {
				// 	document.getElementById("vd_" + this.myvddata.id).srcObject = this.myvddata
				// 		.stream
				// }, 500)
			} else {
				uni.postMessage({
					data: {
						type: "closeVideo",
						payload: {
							roomId: this.roomId
						}
					}
				});
			}
		},
		subStream: async function({
			id,
			name,
			roomId,
			audio,
			video,
			avatar
		}) {
			const _id = this.id
			for (let o of this.dataList) {
				if (o.id == id) {
					return
				}
			}
			const pc = new RTCPeerConnection(null);
			pc.addTransceiver('audio', {
				direction: 'recvonly'
			});
			pc.addTransceiver('video', {
				direction: 'recvonly'
			});
			let offer = await pc.createOffer();
			let stream = new MediaStream();
			pc.ontrack = function(event) {
				console.log(event);
				if (event.track.kind === 'audio' && id == _id) {
					event.track.enabled = false;
				}
				stream.addTrack(event.track);
				
			};
			await pc.setLocalDescription(offer);
			let session = await new Promise(function(resolve, reject) {
				let data = {
					api: `https://dx11.haoleen.com/rtc/v1/play/`,
					tid: id,
					streamurl: `webrtc://dx11.haoleen.com/${roomId}/${id}`,
					clientip: null,
					sdp: offer.sdp,
				};
				console.log('Generated offer: ', data);

				const xhr = new XMLHttpRequest();
				xhr.onload = function() {
					if (xhr.readyState !== xhr.DONE) return;
					if (xhr.status !== 200) return reject(xhr);
					const data = JSON.parse(xhr.responseText);
					console.log('Got answer: ', data);
					return data.code ? reject(xhr) : resolve(data);
				};
				xhr.open('POST', `https://dx11.haoleen.com/rtc/v1/play/`, true);
				xhr.setRequestHeader('Content-type', 'application/json');
				xhr.send(JSON.stringify(data));
			});
			await pc.setRemoteDescription(
				new RTCSessionDescription({
					type: 'answer',
					sdp: session.sdp
				}),
			);

			function close() {
				stream.getTracks().forEach(function(track) {
					track.stop();
					stream.removeTrack(track);
				});
				// stream.close()
				pc.close();
				document.getElementById("vd_" + id).srcObject = null
			}

			const vdata = {
				id,
				roomId,
				pc,
				stream,
				name,
				avatar,
				audio: audio ?? false,
				video: video ?? false,
				close,
			};

			this.dataList.push(vdata)
			setTimeout(() => {
				document.getElementById("vd_" + id).srcObject = stream
			}, 1500)
		},
		publishStream: async function(options) {
			const id = this.id
			const roomId = this.roomId
			const name = this.name
			const pc = new RTCPeerConnection(null);
			pc.addTransceiver('audio', {
				direction: 'sendonly'
			});
			pc.addTransceiver('video', {
				direction: 'sendonly'
			});
			const stream = await navigator.mediaDevices.getUserMedia({
				audio: true,
				video: {
					facingMode: options.videoType ?? "environment"
				},
			});
			this.cameraType = options.videoType ?? "environment"
			console.log(stream);
			stream.getTracks().forEach(function(track) {
				pc.addTrack(track);
				if (track.kind === 'audio') {
					if (options.audio === false) {
						track.enabled = false;
					}
				}
				if (track.kind === 'video') {
					if (options.video === false) {
						track.enabled = false;
					}
				}
			});
			let offer = await pc.createOffer();
			await pc.setLocalDescription(offer);
			let session = await new Promise(function(resolve, reject) {
				let data = {
					api: `https://dx11.haoleen.com/rtc/v1/publish/`,
					tid: id,
					streamurl: `webrtc://dx11.haoleen.com/${roomId}/${id}`,
					clientip: null,
					sdp: offer.sdp,
				};
				console.log('Generated offer: ', data);

				const xhr = new XMLHttpRequest();
				xhr.onload = function() {
					if (xhr.readyState !== xhr.DONE) return;
					if (xhr.status !== 200) return reject(xhr);
					const data = JSON.parse(xhr.responseText);
					console.log('Got answer: ', data);
					if (data.code === 400) {
						resolve(false);
					}
					return data.code ? reject(xhr) : resolve(data);
				};
				xhr.open('POST', `https://dx11.haoleen.com/rtc/v1/publish/`, true);
				xhr.setRequestHeader('Content-type', 'application/json');
				xhr.send(JSON.stringify(data));
			});
			console.log(session);
			if (session === false) {

				uni.postMessage({
					data: {
						type: "exitmtroom",
						payload: {

						}
					}
				});
				uni.switchTab({
					url: "/pages/meeting/index"
				})
				return false;
			}
			await pc.setRemoteDescription(
				new RTCSessionDescription({
					type: 'answer',
					sdp: session.sdp
				}),
			);

			function muteAudio(type) {
				stream.getTracks().forEach(function(track) {
					if (track.kind === 'audio') {
						track.enabled = type ?? false;
					}
				});
			}

			function muteVideo(type) {
				stream.getTracks().forEach(function(track) {
					if (track.kind === 'video') {
						track.enabled = type ?? false;
					}
				});
			}
			const _this = this
			async function unpublish() {
				try {
					stream.getTracks().forEach(function(track) {
						track.stop();
						stream.removeTrack(track);
					});
					// stream.close()
					pc.close();
					document.getElementById("vd_" + id).srcObject = null
				} catch (e) {
					//TODO handle the exception
				}
				_this.dataList = _this.dataList.filter(e => e.id != _this.id)
				// const cid = await getPublishCidById(options.roomId, options.id);
				// console.log(cid);
				// const ret = await axios.delete(
				//   `${process.env.srsUrl}/api/v1/clients/${cid}`,
				// );
			}

			const vdata = {
				id: id,
				name: name,
				roomId: roomId,
				pc,
				stream,
				audio: options.audio == false ? false : true,
				video: options.video == false ? false : true,
				user: {
					id,
					name
				},
				muteAudio,
				muteVideo,
				unpublish: unpublish,
			};
			this.dataList.push(vdata)
			this.myvddata = vdata
			setTimeout(() => {
				uni.postMessage({
					data: {
						type: "pubstreamdone",
						payload: {
							id: id,
							name: name,
							roomId: roomId,
							video: vdata.video,
							audio: vdata.audio
						}
					}
				});
				document.getElementById("vd_" + id).srcObject = stream
			}, 2000)
		},
		publishScreenStream: async function(options) {
			const id = this.id
			const roomId = this.roomId
			const name = this.name
			const pc = new RTCPeerConnection(null);
			pc.addTransceiver('audio', {
				direction: 'sendonly'
			});
			pc.addTransceiver('video', {
				direction: 'sendonly'
			});
			let stream
			if (navigator.getDisplayMedia) {
				stream = await navigator.getDisplayMedia({
					audio: false,
					video: true
				});
			} else if (navigator.mediaDevices.getDisplayMedia) {
				stream = await navigator.mediaDevices.getDisplayMedia({
					audio: false,
					video: true
				});
			} else {
				stream = await navigator.mediaDevices.getUserMedia({
					audio: false,
					video: { mediaSource: 'screen' }
				});
			}
			
			console.log(stream);
			stream.getTracks().forEach(function(track) {
				pc.addTrack(track);
				if (track.kind === 'audio') {
					if (options.audio === false) {
						track.enabled = false;
					}
				}
				if (track.kind === 'video') {
					if (options.video === false) {
						track.enabled = false;
					}
				}
			});
			let offer = await pc.createOffer();
			await pc.setLocalDescription(offer);
			let session = await new Promise(function(resolve, reject) {
				let data = {
					api: `https://dx11.haoleen.com/rtc/v1/publish/`,
					tid: id,
					streamurl: `webrtc://dx11.haoleen.com/${roomId}/${id}`,
					clientip: null,
					sdp: offer.sdp,
				};
				console.log('Generated offer: ', data);

				const xhr = new XMLHttpRequest();
				xhr.onload = function() {
					if (xhr.readyState !== xhr.DONE) return;
					if (xhr.status !== 200) return reject(xhr);
					const data = JSON.parse(xhr.responseText);
					console.log('Got answer: ', data);
					if (data.code === 400) {
						resolve(false);
					}
					return data.code ? reject(xhr) : resolve(data);
				};
				xhr.open('POST', `https://dx11.haoleen.com/rtc/v1/publish/`, true);
				xhr.setRequestHeader('Content-type', 'application/json');
				xhr.send(JSON.stringify(data));
			});
			console.log(session);
			if (session === false) {

				uni.postMessage({
					data: {
						type: "exitmtroom",
						payload: {

						}
					}
				});
				uni.switchTab({
					url: "/pages/meeting/index"
				})
				return false;
			}
			await pc.setRemoteDescription(
				new RTCSessionDescription({
					type: 'answer',
					sdp: session.sdp
				}),
			);

			function muteAudio(type) {
				stream.getTracks().forEach(function(track) {
					if (track.kind === 'audio') {
						track.enabled = type ?? false;
					}
				});
			}

			function muteVideo(type) {
				stream.getTracks().forEach(function(track) {
					if (track.kind === 'video') {
						track.enabled = type ?? false;
					}
				});
			}
			const _this = this
			async function unpublish() {
				try {
					stream.getTracks().forEach(function(track) {
						track.stop();
						stream.removeTrack(track);
					});
					// stream.close()
					pc.close();
					document.getElementById("vd_" + id).srcObject = null
				} catch (e) {
					//TODO handle the exception
				}
				_this.dataList = _this.dataList.filter(e => e.id != _this.id)
				// const cid = await getPublishCidById(options.roomId, options.id);
				// console.log(cid);
				// const ret = await axios.delete(
				//   `${process.env.srsUrl}/api/v1/clients/${cid}`,
				// );
			}

			const vdata = {
				id: id,
				name: name,
				roomId: roomId,
				pc,
				stream,
				audio: options.audio == false ? false : true,
				video: options.video == false ? false : true,
				user: {
					id,
					name
				},
				muteAudio,
				muteVideo,
				unpublish: unpublish,
			};
			this.dataList.push(vdata)
			this.myvddata = vdata
			setTimeout(() => {
				uni.postMessage({
					data: {
						type: "pubstreamdone",
						payload: {
							id: id,
							name: name,
							roomId: roomId,
							video: vdata.video,
							audio: vdata.audio
						}
					}
				});
				document.getElementById("vd_" + id).srcObject = stream
			}, 2000)
		}
	}
})